package Problem2;

class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode a;
        ListNode b;
        // 将 a、b 链表每一位相加
        for (a = l1 , b = l2; a != null && b != null ; a = a.next , b = b.next){
            a.val = b.val = a.val + b.val;
        }
        // 选出长的链表作为主链
        if (a == null){
            a = b = l2;
        }else {
            a = b = l1;
        }
        //做 10进1 处理
        int n = 0;
        while (a != null){
            a.val += n;
            if (a.val >= 10){
                n = 1;
                a.val -= 10;
                //如果结尾10进1，就新建立一个节点1
                if (a.next == null){
                    a.next = new ListNode(1);
                    break;
                }
            }
            else {
                n = 0;
            }
            a = a.next;
        }
        return b;
    }
}
